package com.heima.search.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.context.BaseContext;
import com.heima.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.HistoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HistoryServiceImpl implements HistoryService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 加载用户搜索记录列表
     *
     * @return 用户搜索记录
     */
    @Override
    public List<ApUserSearch> load() {
        Long userId = BaseContext.getCurrentId();
        //用户是否登录
        if (userId == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //用户已登录,加载搜索记录列表
        Query query =
                Query.query(Criteria.where("userId").is(userId))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
        return apUserSearchList;
    }

    /**
     * 删除用户搜索记录
     *
     * @param historySearchDto 搜索记录id
     */
    @Override
    public void del(HistorySearchDto historySearchDto) {
        //用户是否登录
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //参数校验
        if (historySearchDto == null || StringUtils.isEmpty(historySearchDto.getId())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Query query = Query.query(
                Criteria.where("id").is(historySearchDto.getId())
                        .and("userId").is(userId)
        );
        mongoTemplate.remove(query,ApUserSearch.class);
    }
}
